package com.xinzhi.seckill.exception;

import com.xinzhi.seckill.vo.RespBean;
import com.xinzhi.seckill.vo.RespBeanEnum;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;


/**
 * 全局异常处理类
 */
@RestControllerAdvice
//当自定义类加@RestControllerAdvice注解时，方法自动返回json数据，每个方法无需再添加@ResponseBody注解：
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public RespBean ExceptionHandler(Exception e){
        if (e instanceof GlobalException){
            //将异常强转为全局异常
            GlobalException  ex = (GlobalException) e;
            //正常去抛异常
            return RespBean.error(ex.getRespBeanEnum());
        }else if(e instanceof BindException){
            //强转绑定异常
            BindException ex = (BindException) e;
            RespBean respBean =  RespBean.error(RespBeanEnum.BINE_ERROR);
            respBean.setMessage("参数校验异常"+ex.getBindingResult().getAllErrors().get(0).getDefaultMessage());
            return respBean;
        }
        return RespBean.error(RespBeanEnum.ERROR);
    }
}
